package com.itmuch.usercenter.auth;

import com.itmuch.usercenter.security.SecurityException;
import com.itmuch.usercenter.util.JwtOperator;
import io.jsonwebtoken.Claims;
import javax.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author caiqian
 * @date 2021/5/11 10:20
 */
@Aspect
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CheckLoginAspect {

  private final JwtOperator jwtOperator;

  @Around("@annotation(com.itmuch.usercenter.auth.CheckLogin)")
  public Object checkLogin(ProceedingJoinPoint point) {
    try {
      //1 从header 获取token
      RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
      ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
      HttpServletRequest request = attributes.getRequest();
      String token = request.getHeader("x-token");

      // 2 校验token, 如果不合法或者过期 则抛出异常,合法则放行
      Boolean isValid = jwtOperator.validateToken(token);

      //3 如果校验成功,就将用户的信息设置request的Attributes中
      Claims claims = jwtOperator.getClaimsFromToken(token);
      request.setAttribute("id", claims.get("id"));
      request.setAttribute("wxNickName", claims.get("wxNickName"));
      request.setAttribute("role", claims.get("role"));

      if (!isValid) {
        throw new SecurityException("token不合法");
      }

      return point.proceed();
    } catch (Throwable throwable) {
      throw new SecurityException("token非法!");
    }
  }

}
